import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  registerForm: FormGroup

  formErrors = {
    'username': '',
    'password': '',
    'repassword': ''
  }

  validationMessages = {
    'username': {
      'required': '用户名必须输入。',
      'minlength': '用户名4到32个字符。'
    },
    'password': {
      'required': '密码必须输入。',
      'minlength': '密码至少要8位。'
    },
    'repassword': {
      'required': '重复密码必须输入。',
      'minlength': '密码至少要8位。',
      'validateEqual': "两次输入的密码不一致。"
    }
  }

  constructor(private fb: FormBuilder) {
    this.createForm()
  }

  createForm() {
    this.registerForm = this.fb.group({
      username: ['', [
        Validators.required,
        Validators.minLength(4),
        Validators.maxLength(32)
      ]],
      password: ['', [
        Validators.required,
        Validators.minLength(8)
      ]],
      repassword: ['', [
        Validators.required,
        Validators.minLength(8)
      ]]
    })

    this.registerForm.valueChanges
      .subscribe(data => this.onValueChanged());
  }

  onValueChanged(dirty?) {
    if (!this.registerForm) {
      return;
    }
    const form = this.registerForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if(dirty){
        control.markAsDirty()
      }
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  ngOnInit() {
  }

  doRegister(){
    this.onValueChanged()
  }

}
